
package com.funo.increment;

import android.content.Context;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;

/**
 * 增加一个电源锁的类。
 * @author suchangjun
 *
 */
public class PowerLock {

    private WakeLock mWakeLock;
    private String who="";
    /**
     * 获取电源锁。
     * @param context
     * @param name
     */
    public PowerLock(Context context,String name) {
        who=(name!=null?name:"not set name ");
        createWakeLock(context);
    }

    /**
     * 创建唤醒系统不休眠的锁
     * 
     * @param context
     */
    private void createWakeLock(Context context) {
        try {
            if (mWakeLock == null) {
                PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
                mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, who+"PowerLock Connectivity");
                mWakeLock.setReferenceCounted(false);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取唤醒系统不休眠的锁
     */
    public void acquireWakeLock() {
        try {
            if (!isWakeLock()) {
                mWakeLock.acquire();
            }
        } catch (Exception e) {
            if (e != null) {
                e.printStackTrace();
            }
        }
        Log.e("PowerLock", who+"     acquireWakeLock");
    }

    /**
     * 释放唤醒系统不休眠的锁
     */
    public void releaseWakeLock() {
        try {
            if (isWakeLock()) {
                mWakeLock.release();
                Log.e("PowerLock", who+"   releaseWakeLock");

            }
        } catch (Exception e) {
            if (e != null) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 是否处于锁定状态。
     */
    private boolean isWakeLock() {
        if (mWakeLock != null && mWakeLock.isHeld()) {
            return true;
        } else {
            return false;
        }
    }

}
